package com.roy;

import com.sun.xml.internal.ws.util.ByteArrayBuffer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.SecureClassLoader;

/**
 * @author xiaoxiaokui
 * @description
 * 从.myclass文件中加载对象
 * @date 2021/11/21
 */
public class SalaryClassLoader extends SecureClassLoader {

    /**
     * 文件路径
     */
    private String classPath;

    public SalaryClassLoader(String classPath) {
        this.classPath = classPath;
    }

    /**
     * 需要实现从.myclass文件中加载
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String filePath = this.classPath + name.replace(".", "\\").concat(".myclass");
        FileInputStream fis;
        ByteArrayBuffer ba = new ByteArrayBuffer();
        byte[] b;
        int code;
        try {
            fis = new FileInputStream(new File(filePath));
            while ((code = fis.read()) != -1) {
                ba.write(code);
            }
            b = ba.toByteArray();
            return this.defineClass(name, b, 0, b.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("自定义类文件不存在");
        }
    }
}
